package com.acme.logging;

import org.slf4j.ILoggerFactory;
import org.slf4j.Logger;

import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Created by Matveev Alexander on 13.12.13.
 */
public class MyLoggerFactory implements ILoggerFactory {

    private ConcurrentHashMap<String, MyLogger> loggers = new ConcurrentHashMap<String, MyLogger>();

    private static LogWriter writer;
    private static LogFormatter formatter;

    private static MyLogger.Level logLevel;

    static {
        Properties prop = new Properties();
        try {
            //load a properties file
            prop.load(new FileInputStream("config.properties"));

            //get the property value and print it out
            String pattern = prop.getProperty("logging.pattern");
            formatter = new LogFormatter(pattern);

            String output = prop.getProperty("logging.output");
            if (output.equals("")) {
                writer = new ConsoleLogWriter();
            } else {
                writer = new FileLogWriter(output);
            }

            logLevel = MyLogger.Level.valueOf(prop.getProperty("logging.level").toUpperCase());

        } catch (Exception ex) {
            formatter = new LogFormatter("%d %l %p [%t]: %m");
            writer = new ConsoleLogWriter();
            logLevel = MyLogger.Level.DEBUG;
        }
    }

    @Override
    public Logger getLogger(String s) {
        Logger logger = loggers.putIfAbsent(s,new MyLogger(s, writer, formatter, logLevel));
        if(logger==null){
            return loggers.get(s);
        }else {
            return logger;
        }

    }
}
